/* $RCSFile: UrlDataType.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/DataTypes/UrlDataType.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:29  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.IO;
using System.ComponentModel;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

using AddonNice.Core;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Configuration;
using AddonNice.Diagnostics;

namespace AddonNice.UI.DataTypes
{
    #region Special TraceSwitch for all UrlDataType related func
    public class UrlDataTypeTraceSwitch : ADNTraceSwitch
    {
        static public ADNTraceSwitch Sw = new ADNTraceSwitch("UrlDataTypeTrace", "Trace Switch for DataType");
    }
    #endregion TraceSwitch for all DataType related func

    /// <summary>
	/// UrlDataType
	/// </summary>
	public class UrlDataType : BaseDataType
	{
		public UrlDataType()
		{
			InnerDataType   =   PropertiesDataType.String;
			innerValue      =   "http://localhost";
		}

		public override string Value2Save
		{
			get
			{
				return innerValue;
			}
		}
		public override string Val
		{
			get
			{
				string	val	                =	innerValue;
				if ( UrlDataTypeTraceSwitch.Sw.TraceVerbose )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UrlDataType Val GET BEG val: '{0}'",val),UrlDataTypeTraceSwitch.Sw.Info);
			    if ( string.IsNullOrEmpty(innerValue) || ( HttpContext.Current != null ) )
				    return val;
			    Uri Add		                =	null;
				try
				{
					if ( innerValue.StartsWith("~/") )
					{
						// CS 13/10/04 pb with double http prefix
						string wpt	=	HttpUrlBuilder.BuildUrl(innerValue);
						if ( wpt.StartsWith("http://") )
							wpt		=	wpt.Substring(7);
						else if ( wpt.StartsWith("https://") )
							wpt		=	wpt.Substring(8);
		                if ( UrlDataTypeTraceSwitch.Sw.TraceVerbose )
                            Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UrlDataType Val GET wpt: '{0}'",wpt),UrlDataTypeTraceSwitch.Sw.Info);
						val			=	HttpContext.Current.Request.Url.Scheme+"://"+wpt;
		                if ( UrlDataTypeTraceSwitch.Sw.TraceVerbose )
                            Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UrlDataType Val GET val: '{0}'",val),UrlDataTypeTraceSwitch.Sw.Info);
					}
					else if ( innerValue.StartsWith("/"))
					{
						val			=	HttpContext.Current.Request.Url.Scheme+"://"+HttpContext.Current.Request.Url.Authority+innerValue;
		                if ( UrlDataTypeTraceSwitch.Sw.TraceVerbose )
                            Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UrlDataType Val GET val: '{0}'",val),UrlDataTypeTraceSwitch.Sw.Info);
					}
					Add		        =	new Uri(val);
					string sh	    =	Add.Scheme+"://";
                    string sh1      =   sh+HttpContext.Current.Request.Url.Authority;
	                if ( UrlDataTypeTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UrlDataType Val GET sh: '{0}', sh1: '{0}'",sh,sh1),UrlDataTypeTraceSwitch.Sw.Info);
					if ( !val.StartsWith(sh1) )
					{
						val		    =	sh1;
						if ( HttpContext.Current.Request.Url.Authority == "localhost" )
						{
							for (int i=0 ; i < HttpContext.Current.Request.Url.Segments.GetUpperBound(0) && i < 2 ; i++ )
							{
								val	=	val+HttpContext.Current.Request.Url.Segments[i];
							}
						}
	                    if ( UrlDataTypeTraceSwitch.Sw.TraceVerbose )
                            Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UrlDataType Val GET Add.PathAndQuery: '{0}'",Add.PathAndQuery),UrlDataTypeTraceSwitch.Sw.Info);
						if ( val.EndsWith("/") && Add.PathAndQuery.StartsWith("/") )
							val	    +=	Add.PathAndQuery.Substring(1);
						else	val	+=	Add.PathAndQuery;
		                if ( UrlDataTypeTraceSwitch.Sw.TraceVerbose )
                            Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UrlDataType Val GET val: '{0}'",val),UrlDataTypeTraceSwitch.Sw.Info);
						Add		    =	new Uri(val);
					}
					val             =   Add.ToString(); 
	                if ( UrlDataTypeTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UrlDataType Val GET val: '{0}'",val),UrlDataTypeTraceSwitch.Sw.Info);
				}
				catch(Exception ex )
				{
					if ( UrlDataTypeTraceSwitch.Sw.TraceError )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]UrlDataType GET ex : {0}",ex),UrlDataTypeTraceSwitch.Sw.Info);
                    throw;
				}
				// To adapt to global settings for this portal: Cf ADNUrlBuilderProvider
                // When portal is secured, transform any secured folder from http to https url
			    // When portal is NOT secured, transform any secured folder from https to http url
				PortalSettings currentSetting   =   null;
				object	ob	                    =	HttpContext.Current.Items[StStr.strPortalSettings];
				if ( ob != null)
				{
					currentSetting              =   (PortalSettings) ob;
	                if ( UrlDataTypeTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UrlDataType Val GET PortalIsSecured: {0}",currentSetting.PortalIsSecured),UrlDataTypeTraceSwitch.Sw.Info);
                    string[] PortalSecuredDirs  =   currentSetting.PortalSecuredDirs;
                    // Extract the subfolder portion if available
                    string targetPage           =   Add.AbsolutePath.TrimStart(new char[]{'/'});
	                if ( UrlDataTypeTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UrlDataType Val GET targetPage: {0}",targetPage),UrlDataTypeTraceSwitch.Sw.Info);
                    int idx                     =   targetPage.IndexOf('/');
                    if ( idx> 0 )
                        targetPage              =   targetPage.Substring(0,idx);
                    string tg					=	targetPage.ToLower();
	                if ( UrlDataTypeTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UrlDataType Val GET tg: {0}",tg),UrlDataTypeTraceSwitch.Sw.Info);

					if ( currentSetting.PortalIsSecured )
					{
				        foreach(string str in PortalSecuredDirs)
				        {
	                        if ( UrlDataTypeTraceSwitch.Sw.TraceVerbose )
                                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UrlDataType Val GET tg: '{0}', str: '{1}'",tg,str),UrlDataTypeTraceSwitch.Sw.Info);
					        if ( tg.StartsWith(str.ToLower()) )
					        {
						        if ( val.StartsWith("http:",StringComparison.InvariantCultureIgnoreCase) )
							        val	        =	"https"+ val.Substring(4);
						        else if ( !val.StartsWith("https:",StringComparison.InvariantCultureIgnoreCase) )
							        val	        =	"https:"+val;
						        break;
					        }
				        }
					}
					else
					{
					    foreach(string str in PortalSecuredDirs)
					    {
	                        if ( UrlDataTypeTraceSwitch.Sw.TraceVerbose )
                                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UrlDataType Val GET tg: '{0}', str: '{1}'",tg,str),UrlDataTypeTraceSwitch.Sw.Info);
						    if ( tg.StartsWith(str.ToLower()) )
						    {
						        if ( val.StartsWith("https:",StringComparison.InvariantCultureIgnoreCase) )
							        val	        =	"http"+ val.Substring(5);
						        else if ( !val.StartsWith("http:",StringComparison.InvariantCultureIgnoreCase) )
							        val	        =	"http:"+val;
							    break;
						    }
					    }
					}
	                if ( UrlDataTypeTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UrlDataType Val GET val: '{0}'",val),UrlDataTypeTraceSwitch.Sw.Info);
				}
                if ( UrlDataTypeTraceSwitch.Sw.TraceVerbose )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UrlDataType Val GET END val: '{0}'",val),UrlDataTypeTraceSwitch.Sw.Info);
				return val;
			}
			set
			{
                if ( UrlDataTypeTraceSwitch.Sw.TraceVerbose )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UrlDataType Val SET value: '{0}'",value),UrlDataTypeTraceSwitch.Sw.Info);
				//Check type
				try
				{
					if ( !string.IsNullOrEmpty(value)) 
					{
						string	val	    =	value;
						if ( value.StartsWith("~/") || value.StartsWith("/"))
						{
							innerValue	=   value;
						}
                        else
                        {
						    Uri Add		    =	new Uri(val);
						    innerValue      =   Add.ToString(); 
						}
					}
					else 	innerValue	=   string.Empty; 
                    if ( UrlDataTypeTraceSwitch.Sw.TraceVerbose )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]UrlDataType Val SET END innerValue: '{0}'",innerValue),UrlDataTypeTraceSwitch.Sw.Info);
				}
				catch(Exception ex )
				{
					if ( UrlDataTypeTraceSwitch.Sw.TraceError )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]UrlDataType Val SET ex : {0}",ex),UrlDataTypeTraceSwitch.Sw.Info);
					throw;
				}
			}
		}

		public override string Description
		{
			get
			{
				return "Full valid URI";
			}
		}
	}
}